/*
 * MainView.java
 */

package com.fsts.server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;

import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;

import org.jdesktop.application.Action;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.TaskMonitor;

import com.fsts.util.Constant;


public class MainView extends FrameView {

	private JDialog aboutBox;

	private javax.swing.JMenuItem aboutMenuItem;

	private int busyIconIndex = 0;

	private final Icon[] busyIcons = new Icon[15];

	private final Timer busyIconTimer;

	private javax.swing.JButton clearButton;
	private javax.swing.JButton exitButton;
	private javax.swing.JMenuItem exitMenuItem;
	private javax.swing.JMenu fileMenu;
	private javax.swing.JMenu helpMenu;
	private final Icon idleIcon;
	private javax.swing.JLabel infoLabel;
	private javax.swing.JTextArea infoTextArea;
	private javax.swing.JButton initButton;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JPanel mainPanel;
	private javax.swing.JMenuBar menuBar;
	private final Timer messageTimer;
	private javax.swing.JLabel onlineUserLabel;
	private javax.swing.JScrollPane onlineUserScrollPane1;
	private javax.swing.JProgressBar progressBar;
	private javax.swing.JLabel statusAnimationLabel;
	private javax.swing.JLabel statusMessageLabel;

	private javax.swing.JPanel statusPanel;

	public MainView(SingleFrameApplication app) {
		super(app);

		initComponents();

		ResourceMap resourceMap = getResourceMap();
		int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
		messageTimer = new Timer(messageTimeout, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				statusMessageLabel.setText("");
			}
		});
		messageTimer.setRepeats(false);
		int busyAnimationRate = resourceMap
				.getInteger("StatusBar.busyAnimationRate");
		for (int i = 0; i < busyIcons.length; i++) {
			busyIcons[i] = resourceMap
					.getIcon("StatusBar.busyIcons[" + i + "]");
		}
		busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
				statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
			}
		});
		idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
		statusAnimationLabel.setIcon(idleIcon);
		progressBar.setVisible(false);

		TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
		taskMonitor
				.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
					public void propertyChange(
							java.beans.PropertyChangeEvent evt) {
						String propertyName = evt.getPropertyName();
						if ("started".equals(propertyName)) {
							if (!busyIconTimer.isRunning()) {
								statusAnimationLabel.setIcon(busyIcons[0]);
								busyIconIndex = 0;
								busyIconTimer.start();
							}
							progressBar.setVisible(true);
							progressBar.setIndeterminate(true);
						} else if ("done".equals(propertyName)) {
							busyIconTimer.stop();
							statusAnimationLabel.setIcon(idleIcon);
							progressBar.setVisible(false);
							progressBar.setValue(0);
						} else if ("message".equals(propertyName)) {
							String text = (String) (evt.getNewValue());
							statusMessageLabel.setText((text == null) ? ""
									: text);
							messageTimer.restart();
						} else if ("progress".equals(propertyName)) {
							int value = (Integer) (evt.getNewValue());
							progressBar.setVisible(true);
							progressBar.setIndeterminate(false);
							progressBar.setValue(value);
						}
					}
				});
	}

	/**
	 * 清理按钮
	 * 
	 * @param evt
	 */
	private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
		infoTextArea.setText("");
	}

	/**
	 * 初始化按钮
	 * 
	 * @param evt
	 */
	private void initButtonActionPerformed(java.awt.event.ActionEvent evt) {
		// 设置初始化按钮不可用
		
		//new TrustedCenter().init();
//		
		infoTextArea.setText("初始化...\n");
//		JList jd = new JList();
//		String[] userList = new String[3];
//		userList[0] = "Me";
//		userList[1] = "You";
//		userList[2] = "She";
//		
//		jd.setListData(userList);
	//	onlineUserLabel.add("");
		// TODO ...
		onlineUserLabel.setVisible(true);
		new Thread() {
			public void run() {
				try {
					TimeUnit.SECONDS.sleep(2);
				} catch (Exception e) {
					e.printStackTrace();
				}
				//infoTextArea.append("初始化成功...\n");
				
/**********************************************/
				ServerSocket ss = null;
				try {
					TrustedCenter server = new TrustedCenter(infoTextArea);
					ss = new ServerSocket(Constant.LISTENING_PORT);
					infoTextArea.append("监听在"+ss.getLocalPort()+"端口...\n");
					Socket s = null;
					server.init();
					while (true) {
						s = ss.accept(); // 循环接收用户的请求
						infoTextArea.append("一个新的用户登录:" + s.getInetAddress() + "\r\n");
						TrustedCenterHandler h = new TrustedCenterHandler(s);
						server.handlers.add(h);
						h.setHandlers(server.handlers);
						Thread t = new Thread(h);
						t.start();
						// 让handler类处理相关的类别
					}

				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						ss.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
/**********************************************/				
			}
		}.start();

	}

	private void initComponents() {
		mainPanel = new javax.swing.JPanel();
		onlineUserScrollPane1 = new javax.swing.JScrollPane();
		jScrollPane2 = new javax.swing.JScrollPane();
		infoTextArea = new javax.swing.JTextArea();
		initButton = new javax.swing.JButton();
		clearButton = new javax.swing.JButton();
		exitButton = new javax.swing.JButton();
		onlineUserLabel = new javax.swing.JLabel();
		infoLabel = new javax.swing.JLabel();
		menuBar = new javax.swing.JMenuBar();
		fileMenu = new javax.swing.JMenu();
		exitMenuItem = new javax.swing.JMenuItem();
		helpMenu = new javax.swing.JMenu();
		aboutMenuItem = new javax.swing.JMenuItem();
		statusPanel = new javax.swing.JPanel();
		javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
		statusMessageLabel = new javax.swing.JLabel();
		statusAnimationLabel = new javax.swing.JLabel();
		progressBar = new javax.swing.JProgressBar();

		mainPanel.setName("mainPanel"); // NOI18N

		onlineUserScrollPane1.setName("onlineUserScrollPane1"); // NOI18N

		jScrollPane2.setName("jScrollPane2"); // NOI18N

		infoTextArea.setColumns(20);
		infoTextArea.setRows(5);
		infoTextArea.setName("infoTextArea"); // NOI18N
		jScrollPane2.setViewportView(infoTextArea);

		org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application
				.getInstance(com.fsts.server.Main.class).getContext()
				.getResourceMap(MainView.class);
		initButton.setText(resourceMap.getString("initButton.text")); // NOI18N
		initButton.setName("initButton"); // NOI18N
		initButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				initButtonActionPerformed(evt);
			}
		});

		clearButton.setText(resourceMap.getString("clearButton.text")); // NOI18N
		clearButton.setName("clearButton"); // NOI18N
		clearButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				clearButtonActionPerformed(evt);
			}
		});

		javax.swing.ActionMap actionMap = org.jdesktop.application.Application
				.getInstance(com.fsts.server.Main.class).getContext()
				.getActionMap(MainView.class, this);
		exitButton.setAction(actionMap.get("quit")); // NOI18N
		exitButton.setName("exitButton"); // NOI18N

		onlineUserLabel.setText(resourceMap.getString("onlineUserLabel.text")); // NOI18N
		onlineUserLabel.setName("onlineUserLabel"); // NOI18N

		infoLabel.setText(resourceMap.getString("infoLabel.text")); // NOI18N
		infoLabel.setName("infoLabel"); // NOI18N

		javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(
				mainPanel);
		mainPanel.setLayout(mainPanelLayout);
		mainPanelLayout
				.setHorizontalGroup(mainPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								mainPanelLayout
										.createSequentialGroup()
										.addGroup(
												mainPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addGroup(
																mainPanelLayout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				onlineUserScrollPane1,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				119,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jScrollPane2,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				247,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18,
																				18,
																				18)
																		.addGroup(
																				mainPanelLayout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.LEADING)
																						.addComponent(
																								initButton)
																						.addComponent(
																								exitButton)
																						.addComponent(
																								clearButton)))
														.addGroup(
																mainPanelLayout
																		.createSequentialGroup()
																		.addGap(
																				41,
																				41,
																				41)
																		.addComponent(
																				onlineUserLabel)
																		.addGap(
																				127,
																				127,
																				127)
																		.addComponent(
																				infoLabel)))
										.addContainerGap(28, Short.MAX_VALUE)));
		mainPanelLayout
				.setVerticalGroup(mainPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								mainPanelLayout
										.createSequentialGroup()
										.addGap(39, 39, 39)
										.addGroup(
												mainPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																onlineUserLabel)
														.addComponent(infoLabel))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addGroup(
												mainPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																onlineUserScrollPane1,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																205,
																Short.MAX_VALUE)
														.addComponent(
																jScrollPane2,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																205,
																Short.MAX_VALUE))
										.addContainerGap()).addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								mainPanelLayout.createSequentialGroup()
										.addContainerGap(91, Short.MAX_VALUE)
										.addComponent(initButton).addGap(37,
												37, 37).addComponent(
												clearButton).addGap(32, 32, 32)
										.addComponent(exitButton).addGap(46,
												46, 46)));

		menuBar.setName("menuBar"); // NOI18N

		fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
		fileMenu.setName("fileMenu"); // NOI18N

		exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
		exitMenuItem.setName("exitMenuItem"); // NOI18N
		fileMenu.add(exitMenuItem);

		menuBar.add(fileMenu);

		helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
		helpMenu.setName("helpMenu"); // NOI18N

		aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
		aboutMenuItem.setName("aboutMenuItem"); // NOI18N
		helpMenu.add(aboutMenuItem);

		menuBar.add(helpMenu);

		statusPanel.setName("statusPanel"); // NOI18N

		statusMessageLabel.setName("statusMessageLabel"); // NOI18N

		statusAnimationLabel
				.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
		statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

		progressBar.setName("progressBar"); // NOI18N

		javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(
				statusPanel);
		statusPanel.setLayout(statusPanelLayout);
		statusPanelLayout
				.setHorizontalGroup(statusPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addComponent(statusPanelSeparator,
								javax.swing.GroupLayout.DEFAULT_SIZE, 513,
								Short.MAX_VALUE)
						.addGroup(
								statusPanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(statusMessageLabel)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												343, Short.MAX_VALUE)
										.addComponent(
												progressBar,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(statusAnimationLabel)
										.addContainerGap()));
		statusPanelLayout
				.setVerticalGroup(statusPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								statusPanelLayout
										.createSequentialGroup()
										.addComponent(
												statusPanelSeparator,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												2,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												Short.MAX_VALUE)
										.addGroup(
												statusPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.BASELINE)
														.addComponent(
																statusMessageLabel)
														.addComponent(
																statusAnimationLabel)
														.addComponent(
																progressBar,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(3, 3, 3)));

		setComponent(mainPanel);
		setMenuBar(menuBar);
		setStatusBar(statusPanel);
	}

	@Action
	public void showAboutBox() {
		if (aboutBox == null) {
			JFrame mainFrame = Main.getApplication().getMainFrame();
			aboutBox = new MainAboutBox(mainFrame);
			aboutBox.setLocationRelativeTo(mainFrame);
		}
		Main.getApplication().show(aboutBox);
	}
}
